const express = require('express');
const multer = require('multer');
const cors = require('cors');
const fs = require('fs');
const path = require('path');

const app = express();
const PORT = 8080;
const UPLOAD_DIR = path.join(__dirname, 'static', 'uploads');
const DATA_DIR = path.join(__dirname, 'data');

// 确保必要的目录存在
if (!fs.existsSync(UPLOAD_DIR)) {
    fs.mkdirSync(UPLOAD_DIR, { recursive: true });
}
if (!fs.existsSync(DATA_DIR)) {
    fs.mkdirSync(DATA_DIR, { recursive: true });
}

// 配置multer用于文件上传
const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, UPLOAD_DIR);
    },
    filename: function (req, file, cb) {
        const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
        cb(null, uniqueSuffix + path.extname(file.originalname));
    }
});

const upload = multer({ 
    storage: storage,
    fileFilter: function (req, file, cb) {
        const allowedTypes = /jpeg|jpg|png|gif|webp|svg/;
        const extname = allowedTypes.test(path.extname(file.originalname).toLowerCase());
        const mimetype = allowedTypes.test(file.mimetype);
        
        if (mimetype && extname) {
            return cb(null, true);
        } else {
            cb(new Error('只允许上传图片文件！'));
        }
    },
    limits: { fileSize: 10 * 1024 * 1024 } // 10MB限制
});

// 数据存储
const DATA_FILE = path.join(DATA_DIR, 'data.json');

// 初始化数据文件
if (!fs.existsSync(DATA_FILE)) {
    fs.writeFileSync(DATA_FILE, JSON.stringify({
        images: [],
        comments: [],
        likes: {}
    }, null, 2));
}

// 读取数据
function readData() {
    try {
        return JSON.parse(fs.readFileSync(DATA_FILE, 'utf8'));
    } catch (error) {
        return { images: [], comments: [], likes: {} };
    }
}

// 写入数据
function writeData(data) {
    fs.writeFileSync(DATA_FILE, JSON.stringify(data, null, 2));
}

// 中间件
app.use(cors());
app.use(express.json());
app.use(express.static(__dirname));
app.use('/uploads', express.static(UPLOAD_DIR));

// 文件上传接口
app.post('/api/upload', upload.single('image'), (req, res) => {
    try {
        if (!req.file) {
            return res.status(400).json({ success: false, error: '没有上传文件' });
        }

        const data = readData();
        const imageInfo = {
            id: Date.now().toString(),
            filename: req.file.filename,
            original_name: req.file.originalname,
            url: `/uploads/${req.file.filename}`,
            size: req.file.size,
            upload_time: new Date().toISOString(),
            likes: 0,
            comments: 0
        };

        data.images.push(imageInfo);
        writeData(data);

        res.json({ 
            success: true, 
            data: imageInfo,
            message: '图片上传成功！'
        });
    } catch (error) {
        res.status(500).json({ success: false, error: error.message });
    }
});

// 获取图片列表
app.get('/api/images', (req, res) => {
    try {
        const data = readData();
        res.json({ 
            success: true, 
            data: data.images,
            count: data.images.length
        });
    } catch (error) {
        res.status(500).json({ success: false, error: error.message });
    }
});

// 删除图片
app.delete('/api/delete/:filename', (req, res) => {
    try {
        const { filename } = req.params;
        const data = readData();
        
        // 从数据中删除
        const imageIndex = data.images.findIndex(img => img.filename === filename);
        if (imageIndex === -1) {
            return res.status(404).json({ success: false, error: '图片不存在' });
        }

        data.images.splice(imageIndex, 1);
        
        // 删除相关评论
        data.comments = data.comments.filter(comment => comment.image_id !== filename);
        
        // 删除点赞记录
        delete data.likes[filename];
        
        writeData(data);

        // 删除文件
        const filePath = path.join(UPLOAD_DIR, filename);
        if (fs.existsSync(filePath)) {
            fs.unlinkSync(filePath);
        }

        res.json({ success: true, message: '图片删除成功！' });
    } catch (error) {
        res.status(500).json({ success: false, error: error.message });
    }
});

// 获取统计信息
app.get('/api/stats', (req, res) => {
    try {
        const data = readData();
        const totalImages = data.images.length;
        const totalSize = data.images.reduce((sum, img) => sum + img.size, 0);
        const lastUpload = data.images.length > 0 ? 
            Math.max(...data.images.map(img => new Date(img.upload_time).getTime())) : null;

        res.json({ 
            success: true, 
            data: {
                total_images: totalImages,
                total_size: totalSize,
                total_size_formatted: formatFileSize(totalSize),
                last_upload: lastUpload
            }
        });
    } catch (error) {
        res.status(500).json({ success: false, error: error.message });
    }
});

// 点赞功能
app.post('/api/like/:imageId', (req, res) => {
    try {
        const { imageId } = req.params;
        const data = readData();
        
        // 更新点赞数
        if (!data.likes[imageId]) {
            data.likes[imageId] = 0;
        }
        data.likes[imageId]++;
        
        // 更新图片点赞数
        const image = data.images.find(img => img.id === imageId || img.filename === imageId);
        if (image) {
            image.likes = data.likes[imageId];
        }
        
        writeData(data);
        
        res.json({ success: true, likes: data.likes[imageId] });
    } catch (error) {
        res.status(500).json({ success: false, error: error.message });
    }
});

// 获取评论
app.get('/api/comments/:imageId', (req, res) => {
    try {
        const { imageId } = req.params;
        const data = readData();
        const comments = data.comments.filter(comment => comment.image_id === imageId);
        
        res.json({ success: true, data: comments });
    } catch (error) {
        res.status(500).json({ success: false, error: error.message });
    }
});

// 添加评论
app.post('/api/comments', (req, res) => {
    try {
        const { image_id, content, author } = req.body;
        
        if (!image_id || !content) {
            return res.status(400).json({ success: false, error: '缺少必要参数' });
        }

        const data = readData();
        const comment = {
            id: Date.now().toString(),
            image_id,
            content: content.trim(),
            author: author ? author.trim() : '匿名用户',
            created_at: new Date().toISOString()
        };

        data.comments.push(comment);
        
        // 更新图片评论数
        const image = data.images.find(img => img.id === image_id || img.filename === image_id);
        if (image) {
            image.comments = data.comments.filter(c => c.image_id === image_id).length;
        }
        
        writeData(data);
        
        res.json({ success: true, data: comment });
    } catch (error) {
        res.status(500).json({ success: false, error: error.message });
    }
});

// 辅助函数
function formatFileSize(bytes) {
    if (bytes === 0) return '0 Bytes';
    const k = 1024;
    const sizes = ['Bytes', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + ' ' + sizes[i];
}

// 启动服务器
app.listen(PORT, () => {
    console.log(`🚀 杂志图文管理系统服务器启动成功！`);
    console.log(`📍 访问地址: http://localhost:${PORT}`);
    console.log(`📁 上传目录: ${UPLOAD_DIR}`);
    console.log(`📊 数据文件: ${DATA_FILE}`);
    console.log(`🌐 后台管理: http://localhost:${PORT}/backend_admin.html`);
    console.log(`👥 前端展示: http://localhost:${PORT}/gallery.html`);
});